//
//  KindViewController.m
//  Zaker
//
//  Created by lirui on 16/3/10.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "SeeKindViewController.h"
#import "SeeVideoCell.h"
#import <MediaPlayer/MediaPlayer.h>
#import <View+MASAdditions.h>
#import "SeeVideoDetailViewController.h"
#import "CoreDataManager.h"
@interface SeeKindViewController ()<UITableViewDataSource,UITableViewDelegate,playDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic ,retain)NSMutableArray *dataArr;
@property(nonatomic, retain)NSIndexPath *indexpath;
@property (nonatomic, retain)MPMoviePlayerViewController *movieView;
@property (nonatomic, retain)UIButton *button;
@property (nonatomic, assign)BOOL isfull;
@property(nonatomic ,assign)BOOL collect;
@property(nonatomic, strong) CoreDataManager *manager;
@end

@implementation SeeKindViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self dataHandler];
    [self creatView];
    [self notificationVideo];
    self.manager =  [CoreDataManager defaults];
    [self loadMBProgress];

}

-(void)dataHandler
{
    NSString *str = [NSString stringWithFormat:@"http://c.m.163.com/nc/video/list/%@/y/0-10.html",_sid];
    [LHAFNetworkTool  getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        NSArray *arr = [resposeObject objectForKey:_sid];
        self.dataArr = [SeeModel modelHandlerWithArray:arr];
        [_tableView reloadData];
        [self.hud removeFromSuperview];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}
-(void)creatView
{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[SeeVideoCell class] forCellReuseIdentifier:@"kindCell"];
    [self.view addSubview:_tableView];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 300 *HEIGHT;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SeeVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kindCell" forIndexPath:indexPath ];
     cell.selectionStyle = UITableViewCellSelectionStyleNone;
    SeeModel *m = _dataArr[indexPath.row];
    cell.titleLable.text = m.title;
    cell.detailLable.text = m.description1;
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:m.cover]];
    cell.timeLable.text = m.length.stringValue;
    cell.playLable.text = m.playCount.stringValue;
   
    UITapGestureRecognizer *tap = [[ UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [cell.myImageView addGestureRecognizer:tap];
    cell.myImageView.userInteractionEnabled = YES;
    cell.delegate = self;

[cell.share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];

cell.share.tag = indexPath.row;
[cell.likeBtn addTarget:self action:@selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
cell.likeBtn.tag = indexPath.row;
_collect = NO;
cell.likeBtn.selected = NO;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:@"changeLike" object:nil];
return cell;

}
-(void)change:(UIButton *)btn
{
    [_tableView reloadData];
}
-(void)likeAction:(UIButton *)like
{
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Video" inManagedObjectContext:self.manager.managedObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Video"];
    NSError *error;
    NSArray *arr = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
    SeeModel  *model = _dataArr[like.tag];
    _collect = !_collect;
    if (_collect) {
        //设置收藏属性
        like.selected = YES;
        for (Video *m in arr) {
            if ([m.title isEqualToString:model.title]) {
                return;
            }
        }
        Video *top = [[Video alloc] initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
        top.title = model.title;
        top.url = model.mp4_url;
        top.detail = model.description1;
        top.vid = model.vid;
        [self.manager saveContext];
    } else {
        like.selected = NO;
        for (Video *m in arr) {
            if ([m.title isEqualToString:model.title]) {
                [self.manager.managedObjectContext deleteObject:m];
            }
        }
        [self.manager saveContext];
    }
    //NSLog(@"数据库收藏:%@", arr);
    NSLog(@"url === %@", [self.manager applicationDocumentsDirectory]);
    
    
}



-(void)shareAction:(UIButton *)btn
{     NSLog(@"%ld",btn.tag);

    
     [Elastic elastic:[_dataArr[btn.tag] mp4_url]];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SeeVideoDetailViewController *detail =[[ SeeVideoDetailViewController alloc] init];
    detail.sModel = _dataArr[indexPath.row];
    [self.navigationController pushViewController:detail animated:YES];
}
#pragma mark -协议方法
-(void)playMovie:(UITapGestureRecognizer *)p
{
    [self moviePlayer:p];
}
-(void)tapAction:(UITapGestureRecognizer *)t
{
    [self moviePlayer:t];
}
#pragma mark -创建视频播放器
-(void)moviePlayer:(UITapGestureRecognizer *)tap

{if (self.movieView.view) {
    [self.movieView.view removeFromSuperview];
}
    //点击的哪个ImageView
    UIView *view = tap.view;
    //imageView->contentView->cell
    UITableViewCell *cell = (UITableViewCell *)view.superview.superview;
    self.indexpath = [self.tableView indexPathForCell:cell];//获取被点击的cell的indexPath
    SeeModel *model =_dataArr[_indexpath.row];
    self.movieView = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:model.mp4_url]];
    self.movieView.view.frame = CGRectMake(10, 60, [UIScreen mainScreen].bounds.size.width - 20, [UIScreen mainScreen].bounds.size.height / 3 + 8);
    [self.movieView.moviePlayer setControlStyle:(MPMovieControlStyleEmbedded)];
    [self.movieView.moviePlayer setControlStyle:(MPMovieControlStyleEmbedded)];
    [cell addSubview:self.movieView.view];
    
    //添加视频关闭按钮
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
    [self.button setBackgroundImage:[UIImage imageNamed:@"iconfont-cha"] forState:UIControlStateNormal];
    [self.movieView.view addSubview:self.button];
    //设置按钮的相对坐标
    [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.movieView.view).with.offset(-5);
        make.top.equalTo(self.movieView.view.mas_top).with.offset(5);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(20);
    }];
    
}
#pragma mark -关闭
- (void)close:(UIButton *)button {
    [self.movieView.moviePlayer stop];
    [self.movieView.moviePlayer pause];
    [self.movieView.view removeFromSuperview];
}


#pragma mark -通知中心监听视频
-(void)notificationVideo
{
    //视频监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jumpFullScreen) name:@"MPMoviePlayerWillEnterFullscreenNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitFullScreen) name:@"MPMoviePlayerWillExitFullscreenNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removecell) name:@"remove" object:nil];
    
    
}
//通知中心 让视频停掉
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"remove" object:nil];
}
-(void)removecell
{
    if (self.movieView.view) {
        //        self.movieView.moviePlayer.pause;
        [self.movieView.view removeFromSuperview];
    }
}
- (void)jumpFullScreen {
    
    self.isfull = YES;
    
}

- (void)exitFullScreen {
    self.isfull = NO;
}
//将要离开页面时 移除
-(void)viewWillDisappear:(BOOL)animated
{
    if (!self.isfull) {
        if (self.movieView.view) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"remove" object:nil];
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
